from numpy import *
"""
逐行读取文件内的内容


:returns
dataMat 数据集 为方便计算 X0全部赋值为0 X1、X2分别表示为数据的
"""
def loadDataSet():
    dataMat = []; labelMat = []
    file = open('testSet.txt')
    for line in file.readlines():
        lineArr = line.split()
        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
        labelMat.append(int(lineArr[2]))
    return dataMat, labelMat
"""
:param inX 数据


:return sigmoid 函数计算结果
"""
def sigmoid(inX):
    return 1.0 / (1 + exp(inX))
"""
"""
def gradAscent(dataMatin, classLabels):
    dataMatrix = mat(dataMatin)
    labelMat = mat(classLabels).transpose() #转置矩阵
    m, n = shape(dataMatrix)
    alpha = 0.001 #步长
    maxCycles = 500 #最高迭代次数
    weights = ones((n, 1))
    for k in range(maxCycles):
        h = sigmoid(dataMatrix * weights)
        error = (labelMat - h)
        weights = weights + alpha * dataMatrix.transpose() * error
    return weights
"""
画出数据集和拟合曲线
"""
def plotBestFit(weights):
    import matplotlib.pyplot as plt
    dataMat, labelMat = loadDataSet()
    dataArr = array(dataMat)
    n = shape(dataArr)[0]
    print(n)
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelMat[i]) == 1:
            xcord1.append(dataArr[i, 1]); ycord1.append(dataArr[i, 2])
        else:
            xcord2.append(dataArr[i, 1]); ycord2.append(dataArr[i, 2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1, ycord1, s = 30, c = 'red', marker='s')
    ax.scatter(xcord2, ycord2, s = 30, c = 'green')
    xx = []
    x = arange(-3.0, 3.0, 0.1)
    print(x[0])
    y = (-weights[0] - weights[1] * x) / weights[2]
    ax.plot(x[0], y[0])
    plt.xlabel('X1'); plt.ylabel('X2')
    plt.show()


dataMat, labelMat = loadDataSet()
dataMatrix = mat(dataMat)
weights = gradAscent(dataMat, labelMat)
print(weights)
plotBestFit(weights)